package com.xinghai.system.service.impl;


import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.xinghai.common.exception.ServiceException;
import com.xinghai.common.utils.DateUtils;

import com.xinghai.system.domain.entity.QdShopOrderDTO;
import com.xinghai.system.domain.entity.RechargePointsDTO;
import com.xinghai.system.service.IQdUserWalletService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import com.xinghai.common.constant.GenConstants;
import com.xinghai.system.mapper.QdShopOrderMapper;
import com.xinghai.system.domain.QdShopOrder;
import com.xinghai.system.service.IQdShopOrderService;

/**
 * 订单模块Service业务层处理
 *
 * @author xinghai
 * @date 2025-01-26
 */
@Service
public class QdShopOrderServiceImpl extends ServiceImpl<QdShopOrderMapper, QdShopOrder>
        implements IQdShopOrderService
{

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Autowired
    private IQdUserWalletService qdUserWalletService;
    /**
     * 查询订单模块列表
     *
     * @param qdShopOrder 订单模块
     * @return 订单模块集合
     */
    @Override
    public List<QdShopOrder> list(QdShopOrder qdShopOrder) {
        QueryWrapper<QdShopOrder> queryWrapper = new QueryWrapper<>();
        if (qdShopOrder.getStatus()!= null  && !qdShopOrder.getStatus().isEmpty()){
            queryWrapper.eq("status", qdShopOrder.getStatus());
        }
        if (qdShopOrder.getOrderNo()!= null  && !qdShopOrder.getOrderNo().isEmpty()){
            queryWrapper.like("order_no", qdShopOrder.getOrderNo());
        }
        if (qdShopOrder.getBuyerUserId()!= null){
            queryWrapper.eq("buyer_user_id", qdShopOrder.getBuyerUserId());
        }
        if (qdShopOrder.getBuyerUserName()!= null  && !qdShopOrder.getBuyerUserName().isEmpty()){
            queryWrapper.like("buyer_user_name", qdShopOrder.getBuyerUserName());
        }
        if (qdShopOrder.getBuyerUserPhone()!= null  && !qdShopOrder.getBuyerUserPhone().isEmpty()){
            queryWrapper.like("buyer_user_phone", qdShopOrder.getBuyerUserPhone());
        }
        if (qdShopOrder.getBuyerStatus()!= null  && !qdShopOrder.getBuyerStatus().isEmpty()){
            queryWrapper.eq("buyer_status", qdShopOrder.getBuyerStatus());
        }
        if (qdShopOrder.getGoodName()!= null && !qdShopOrder.getGoodName().isEmpty()){
            queryWrapper.like("good_name", qdShopOrder.getGoodName());
        }
        if (qdShopOrder.getStoreId()!= null){
            queryWrapper.eq("store_id", qdShopOrder.getStoreId());
        }
        if (qdShopOrder.getSearchValue()!= null && !qdShopOrder.getSearchValue().isEmpty()){
            queryWrapper.and(m->m.like("good_name", qdShopOrder.getSearchValue()).or().like("buyer_user_phone", qdShopOrder.getSearchValue()).or().like("buyer_user_name", qdShopOrder.getSearchValue()));
        }
        if (qdShopOrder.getParams().get("beginDealTime")!= null && !"".equals(qdShopOrder.getParams().get("beginDealTime"))
        &&qdShopOrder.getParams().get("endDealTime")!= null && !"".equals(qdShopOrder.getParams().get("endDealTime"))){
            queryWrapper.between("deal_time", qdShopOrder.getParams().get("beginDealTime"),qdShopOrder.getParams().get("endDealTime"));
        }
        if (qdShopOrder.getParams().get("beginCreateTime")!= null && !"".equals(qdShopOrder.getParams().get("beginCreateTime"))
                &&qdShopOrder.getParams().get("endCreateTime")!= null && !"".equals(qdShopOrder.getParams().get("endCreateTime"))){
            queryWrapper.between("create_time", qdShopOrder.getParams().get("beginCreateTime"),qdShopOrder.getParams().get("endCreateTime"));
        }
        return this.list(queryWrapper);
    }

    /**
     * 删除订单模块信息
     * @param id 需要删除的数据ID
     * @param flag 是否是逻辑删除
     * @return 结果
     */
    @Override
    public boolean delete(Long id, boolean flag) {
        if (flag){
            QdShopOrder qdShopOrder = new QdShopOrder();
            qdShopOrder.setId(id);
            qdShopOrder.setDelFlag(GenConstants.DELETE_FLAG_YES);
            return this.updateById(qdShopOrder);
        }
        return this.removeById(id);
    }

    /**
     * 批量删除订单模块信息
     *
     * @param ids 需要删除的数据ID集合
     * @param flag 是否是逻辑删除
     * @return 结果
     */
    @Override
    @Transactional
    public boolean deleteBatch(Long[] ids, boolean flag) {
        if (flag){
            List<QdShopOrder> collect = Arrays.stream(ids).map(m -> {
                QdShopOrder qdShopOrder = new QdShopOrder();
                qdShopOrder.setId(m);
                qdShopOrder.setDelFlag(GenConstants.DELETE_FLAG_YES);
                return qdShopOrder;
            }).collect(Collectors.toList());
            return this.updateBatchById(collect);
        }
        return this.removeByIds(Arrays.asList(ids));
    }

    /**
     * 导入订单模块信息
     *
     * @param list 订单模块信息集合
     * @return 结果
     */
    @Override
    @Transactional
    public boolean importData(List<QdShopOrder> list){
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        try {
            QdShopOrderMapper qdShopOrderMapper = sqlSession.getMapper(QdShopOrderMapper.class);
            list.forEach(qdShopOrderMapper::insert);
            // 提交数据
            sqlSession.commit();
            sqlSession.rollback();
        } catch (Exception e) {
            sqlSession.rollback();
            return false;
        } finally {
            sqlSession.close();
        }
        return true;
    }

    @Override
    @Transactional
    public boolean cancelOrder(QdShopOrderDTO dto) {
        //取消订单，修改订单状态
        Long orderId = dto.getOrderId();
        QdShopOrder order = getById(orderId);
        if (!("1".equals(order.getBuyerStatus()) || "2".equals(order.getBuyerStatus()))){
            throw new ServiceException("订单发生变更，无法取消");
        }
        //判断订单是否为待发货阶段，返还相应积分
        if ("2".equals(order.getBuyerStatus())){
            //扣除商品积分
            //积分记录
            RechargePointsDTO dto1 = new RechargePointsDTO();
            dto1.setUserId(order.getBuyerUserId().toString());
            //减少
            dto1.setPoints(order.getPoints().multiply(new BigDecimal(-1)));
            dto1.setDetail("订单取消，退回积分");
            dto1.setType("4");
            qdUserWalletService.rechargePoints(dto1);
        }
        order.setBuyerStatus("5");
        return updateById(order);
    }

    @Override
    @Transactional
    public boolean confirmPayment(QdShopOrderDTO dto) {
        //确认支付，修改订单状态
        Long orderId = dto.getOrderId();
        QdShopOrder order = getById(orderId);
        if (!"1".equals(order.getBuyerStatus())){
            throw new ServiceException("订单发生变更，无法取消");
        }
        //赠送商品积分
        //积分记录
        RechargePointsDTO dto1 = new RechargePointsDTO();
        dto1.setUserId(order.getBuyerUserId().toString());
        dto1.setPoints(order.getPoints());
        dto1.setDetail("商品购买，获得积分");
        dto1.setType("2");
        qdUserWalletService.rechargePoints(dto1);
        order.setBuyerStatus("2");
        return updateById(order);
    }
}
